<?php
namespace App\Logic;

class RoleLogic
{
    public $m;
    public function __construct()
    {
        $this->m = M('role');
    }

    public function ls()
    {
        $data = $this->m->order('px ASC')->select();
        return array('st' => 1, 'data' => $data);
    }

    public function map()
    {
        $data = $this->m->order('px ASC')->map('name', 'role');   //如果id为键,前端会自动按id排序
        return array('st' => 1, 'data' => $data);
    }
    
    public function get($id)
    {
        $id = (int) $id;
        $row = $this->m->find($id);
        $row['pri'] = $row['pri'] ? json_decode($row['pri'], true) : array();
        return array('st' => 1, 'data' => $row);
    }
    
    public function submit($post)
    {
        $id = (int) $post['id'];
        foreach($post['pri'] as &$p) {
            if($p[0] == '/') $p = substr($p, 1, 99);
        }
        $post['pri'] = array_filter($post['pri']);
        $post['pri'] = array_values($post['pri']);
        $post['pri'] = json_encode($post['pri']);
        //允许编辑字段
        if($id) {
            $allow = array('name','pri','st','role');
            $row = allow_edit($post, $allow);
            $rs = $this->m->where("id = $id")->save($row);
        }else{
            $rs = $this->m->add($post);
        }
        if($rs !== false) {
            return array('st' => 1);
        }else{
            return array('st' => 0, 'msg' => '保存错误');
        }
    }

    //修改状态
    public function st($id, $st)
    {
        $rs = $this->m->where("id = $id")->setField('st', $st);
        if($rs !== false) {
            return array('st' => 1);
        }else{
            return array('st' => 0, 'msg' => '修改状态错误');
        }
    }

    /**
     * 排序
     * @param $ids  array(3,2,40)
     */
    public function px($ids)
    {
        foreach($ids as $k => $id) {
            $id = (int) $id;
            if(!$id) continue;
            $rs = $this->m->where(array('id' => $id))->setField('px', $k + 1);
            if($rs === false) json(0, '保存顺序错误');
        }
        json(1);
    }
}